package com.open.capacity.controller;

import com.open.capacity.common.web.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadFileController {
    @PostMapping("/file")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println("用户上传名：" + originalFilename);
        //后缀名
        String extension = FilenameUtils.getExtension(originalFilename);
        System.out.println("后缀名：" + extension);
        //生成随机名
        String randomID = UUID.randomUUID().toString().replace("-", "");
        System.out.println("生成随机名:" + randomID);
        //连接随机名 后缀名
        String newName = randomID + "." + extension;
        System.out.println("连接随机名 后缀名:"+newName);
        //获取当前路径
        String path = file.getClass().getResource("/").getPath();
        System.out.println("获取当前路径"+path);
        //    /C:/process/business-center/lessors/target/classes/
        //截取路径
        String s = path.split("business-center")[0];
        System.out.println("截取路径:"+s);
        //连接路径
        String newPath = s+"ZBestPC/img/";
        //连接文件路径和文件
        File newFile= new File(newPath , newName);
        //写文件内容到文件中
        file.transferTo(newFile);

        String url ="img/"+newName;

        return Result.succeed(url,"操作成功！");
    }
}
